import wx.grid
import abstractModel


class SimpleName(abstractModel.AbstractModel):
    """
    model的实体类，人名model
    """

    def __init__(self, first="", last=""):
        abstractModel.AbstractModel.__init__(self)
        self.set(first, last)

    def set(self, first, last):
        self.first = first
        self.last = last
        self.update()  # 通知监听方法


class ModelExample(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Flintstones', size=(400, 300))

        panel = wx.Panel(self)
        panel.SetBackgroundColour("White")
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        self.textFields = {}
        self.createTextFileds(panel)
        self.creartBuuttoonBar(panel)

        self.model = SimpleName()  # 创建一个模型，并添加OnUpdate监听方法
        self.model.addListener(self.OnUpdate)

    def buttonData(self):
        return (('Fredify', self.OnFred),
                ('Wilmafy', self.OnWilma),
                ('Barnify', self.OnBarney),
                ('Bettify', self.OnBetty))

    def textFieldData(self):
        return (('FirstName', (10, 50)),
                ('LastName', (10, 80)))

    def createTextFileds(self, parent):
        for eachLabel, eachPos in self.textFieldData():
            self.createCaptionedText(parent, eachLabel, eachPos)

    def createCaptionedText(self, panel, label, pos):
        static = wx.StaticText(panel, -1, label, pos)
        static.SetBackgroundColour("White")
        textPos = (pos[0] + 75, pos[1])
        self.textFields[label] = wx.TextCtrl(panel, -1,
                                             "", size=(100, -1), pos=textPos, style=wx.TE_READONLY)

    def OnUpdate(self, model):
        self.textFields["FirstName"].SetValue(model.first)
        self.textFields["LastName"].SetValue(model.last)

    def creartBuuttoonBar(self, panel, yPos=0):
        xPos = 0

        for eachLabel, eachHandler in self.buttonData():
            pos = (xPos, yPos)
            button = self.buildOneButton(panel, eachLabel, eachHandler, pos)
            xPos += button.GetSize().width

    def buildOneButton(self, parent, label, handler, pos=(0, 0)):
        button = wx.Button(parent, -1, label, pos)
        self.Bind(wx.EVT_BUTTON, handler, button)
        return button

    def OnFred(self, event):
        self.model.set("Fred", "Flintstone")

    def OnBarney(self, event):
        self.model.set("Barney", "Rubble")

    def OnWilma(self, event):
        self.model.set("Wilma", "Flintstone")

    def OnBetty(self, event):
        self.model.set("Betty", "Rubble")

    # ---------------------------------------------
    def OnCloseWindow(self, event):
        self.Destroy()


if __name__ == '__main__':
    app = wx.App()

    frame = ModelExample(parent=None, id=-1)
    frame.Show(True)

    app.MainLoop()
